<?php
class QinUser{
  private $db;
  public function __construct()
  {
    $this->db = QinDb::instance();
    $this->db->exec('set names utf8;');
    Zend_Db_Table::setDefaultAdapter($this->db);
  }

  /* insert a user to user table */
  public function addUser($array)
  {
      if (strpos($array['username'], '@'))
	{
	  $field = 'email';
	  $field_desc = "电子邮件";
	  $array['email'] = $array['username'];
	  unset($array['username']);
	}
      else
	{
	  $field = 'username';
	  $field_desc = "用户名";
	}

    $where = $this->db->quoteInto("$field = ?", $array[$field]);
    $user = new Application_Model_User();
    $usermapper = new Application_Model_UserMapper();
    $usermapper->findObj($where, $user);

    /* check whether user is already exists */
    if ($user && $user->get("id") > 0)
	return array("resp_id"=>"0001", "resp_data"=>array("msg"=>"此".$field_desc."已被使用。"));

    $user = new Application_Model_User();
    $array['password'] = md5($array['password']);
    $user->setOptions($array); /* = new Application_Model_User($array); */
    if ($uid = $usermapper->save($user))
      {
	return array("resp_id"=>"0000", "resp_data"=>array("user_id"=>$uid, "msg"=>"用户注册成功。"));
      }
    else
      {
	return array("resp_id"=>"0000", "resp_data"=>array("msg"=>"注册失败，请稍候再试。"));
      }
  }
};